﻿using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR;

namespace K9Nano.LayIM.Hubs
{
    internal class ChatHubContext : IChatHubContext
    {
        private readonly IHubContext<ChatHub> _hub;
        private readonly IJsonSerializer _jsonSerializer;

        public ChatHubContext(IHubContext<ChatHub> hub, IJsonSerializer jsonSerializer)
        {
            _hub = hub;
            _jsonSerializer = jsonSerializer;
        }

        public void Send(string to, string type, object data)
        {
            _hub.Clients.User(to)
                .SendAsync(Constants.Method_Receive_Message, type, _jsonSerializer.Serialize(data))
                .ConfigureAwait(false)
                .GetAwaiter()
                .GetResult();
        }

        public Task SendAsync(string to, string type, object data)
        {
            return _hub.Clients.User(to)
                .SendAsync(Constants.Method_Receive_Message, type, _jsonSerializer.Serialize(data));
        }

        public Task JoinHubGroupAsync(string group, string connectionId)
        {
            return _hub.Groups.AddToGroupAsync(connectionId, group);
        }

        public Task SendToGroupAsync(string group, string type, object data)
        {
            return _hub.Clients.Group(group)
                .SendAsync(Constants.Method_Receive_Message, type, _jsonSerializer.Serialize(data));
        }

        public Task SendToGroupAsync(string group, string type, object data, string excludedConnectionId)
        {
            return _hub.Clients.GroupExcept(group, excludedConnectionId)
                .SendAsync(Constants.Method_Receive_Message, type, _jsonSerializer.Serialize(data));
        }

        public Task SendToGroupAsync(string group, string type, object data, IReadOnlyList<string> excludedConnectionIds)
        {
            return _hub.Clients.GroupExcept(group, excludedConnectionIds)
                .SendAsync(Constants.Method_Receive_Message, type, _jsonSerializer.Serialize(data));
        }
    }
}